package com.dy.yunying.biz.service.hongbao.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dy.yunying.api.constant.Constant;
import com.dy.yunying.api.entity.hongbao.HbActivity;
import com.dy.yunying.api.entity.hongbao.HbInvestRecord;
import com.dy.yunying.api.req.hongbao.ActivityIdReq;
import com.dy.yunying.api.req.hongbao.ApplyInvestReq;
import com.dy.yunying.api.req.hongbao.InvertMoneyReq;
import com.dy.yunying.api.resp.hongbao.AssetsData;
import com.dy.yunying.api.resp.hongbao.GiftVoData;
import com.dy.yunying.api.resp.hongbao.InvestRecordVo;
import com.dy.yunying.api.resp.hongbao.RedPackCountData;
import com.dy.yunying.biz.dao.ads.hongbao.HbActivityMapper;
import com.dy.yunying.biz.dao.ads.hongbao.HbInvestRecordMapper;
import com.dy.yunying.biz.dao.ads.hongbao.HbReceivingRecordMapper;
import com.dy.yunying.biz.dao.ads.hongbao.HbRedpackConfigMapper;
import com.dy.yunying.biz.service.hongbao.ActivityService;
import com.dy.yunying.biz.service.hongbao.InvestRecordService;
import com.pig4cloud.pig.common.core.mybatis.Page;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.security.util.SecurityUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author yuwenfeng
 * @description: 注资记录服务
 * @date 2021/10/23 10:47
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class InvestRecordServiceImpl extends ServiceImpl<HbInvestRecordMapper, HbInvestRecord> implements InvestRecordService {

	private final HbInvestRecordMapper investRecordMapper;

	private final HbRedpackConfigMapper redpackConfigMapper;

	private final HbReceivingRecordMapper receivingRecordMapper;

	private final ActivityService activityService;

	private final HbActivityMapper activityMapper;

	@Override
	public Page<InvestRecordVo> selectInvestRecordPage(Page<HbInvestRecord> page, QueryWrapper<HbInvestRecord> query) {
		return investRecordMapper.selectVoPage(page, query);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public R addInvestRecord(InvertMoneyReq invertMoneyReq) {
		HbActivity activity = activityMapper.selectById(invertMoneyReq.getActivityId());
		if (null == activity) {
			return R.failed("活动不存在或已删除");
		}
		if (1 != invertMoneyReq.getInvestType() && 3 != invertMoneyReq.getInvestType() && 4 != invertMoneyReq.getInvestType()) {
			return R.failed("注资类型不合法");
		}
		HbInvestRecord info = JSON.parseObject(JSON.toJSONString(invertMoneyReq), HbInvestRecord.class);
		Double investMoney = investRecordMapper.sumInvestMoneyByType(invertMoneyReq.getActivityId(), invertMoneyReq.getInvestType());
		Double expendBalance = receivingRecordMapper.sumExpendBalanceByType(invertMoneyReq.getActivityId(), invertMoneyReq.getInvestType());
		info.setActivityBalance(BigDecimal.valueOf(Objects.isNull(investMoney) ? 0 : investMoney).subtract(BigDecimal.valueOf(Objects.isNull(expendBalance) ? 0 : expendBalance)));
		info.setApplyStatus(Constant.APPLY_WAIT);
		info.setApplyId(SecurityUtils.getUser().getId().longValue());
		info.setApplyTime(new Date());
		info.setCreateTime(new Date());
		info.setCreateId(SecurityUtils.getUser().getId().longValue());
		info.setUpdateTime(new Date());
		info.setUpdateId(SecurityUtils.getUser().getId().longValue());
		investRecordMapper.insert(info);
		return R.ok();
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public R applyInvestRecord(ApplyInvestReq applyInvestReq) {
		HbInvestRecord info = investRecordMapper.selectOne(new QueryWrapper<HbInvestRecord>().eq("id", applyInvestReq.getId()).eq("apply_status", Constant.APPLY_WAIT));
		if (null == info) {
			return R.failed("当前状态无法审核");
		}
		if (Constant.APPLY_SUCC != applyInvestReq.getApplyStatus() && Constant.APPLY_FAIL != applyInvestReq.getApplyStatus()) {
			return R.failed("注资状态不合法");
		}
		info.setApplyStatus(applyInvestReq.getApplyStatus());
		if (StringUtils.isNotBlank(applyInvestReq.getApplyRemarke())) {
			info.setApplyRemarke(applyInvestReq.getApplyRemarke());
		}
		info.setUpdateTime(new Date());
		info.setUpdateId(SecurityUtils.getUser().getId().longValue());
		investRecordMapper.updateById(info);
		activityService.sumActivity(info.getActivityId());
		return R.ok();
	}

	@Override
	public AssetsData selectAssetsCount(ActivityIdReq activityReq) {
		AssetsData result = new AssetsData();
		HbActivity activity = activityMapper.selectById(activityReq.getId());
		if (null != activity) {
			result.setTotalCost(activity.getTotalCost());
			result.setTotalInvestMoney(activity.getTotalInvestMoney());
			result.setExpendBalance(activity.getExpendBalance());
		}
		List<RedPackCountData> activityCountList = generateRedPackCountData();
		List<RedPackCountData> allCountList = redpackConfigMapper.selectMoneyCountList(activityReq.getId());
		if (CollectionUtils.isNotEmpty(allCountList)) {
			for (RedPackCountData redPack : allCountList) {
				if (null != redPack && redPack.getRewardCost().doubleValue() > 0) {
					for (RedPackCountData redPackCountData : activityCountList) {
						if (redPackCountData.getType().equals(redPack.getType())) {
							redPackCountData.setRewardCost(redPack.getRewardCost());
						}
					}
				}
			}
		}
		for (RedPackCountData redPackCountData : activityCountList) {
			Double investMoney = investRecordMapper.sumInvestMoneyByType(activityReq.getId(), redPackCountData.getType());
			redPackCountData.setInvestMoney(BigDecimal.valueOf(Objects.isNull(investMoney) ? 0 : investMoney));
			Double expendBalance = receivingRecordMapper.sumExpendBalanceByType(activityReq.getId(), redPackCountData.getType());
			redPackCountData.setExpendBalance(BigDecimal.valueOf(Objects.isNull(expendBalance) ? 0 : expendBalance));
		}
		result.setActivityCountList(activityCountList);
		List<GiftVoData> giftCountList = redpackConfigMapper.selectGiftList(activityReq.getId(), 2);
		if (CollectionUtils.isNotEmpty(giftCountList)) {
			result.setGiftCountList(giftCountList);
		}
		return result;
	}

	private List<RedPackCountData> generateRedPackCountData() {
		List<RedPackCountData> activityCountList = new ArrayList<RedPackCountData>();
		RedPackCountData redPack;
		for (int i = 1; i < 5; i++) {
			redPack = new RedPackCountData();
			redPack.setType(i);
			redPack.setRewardCost(BigDecimal.ZERO);
			redPack.setInvestMoney(BigDecimal.ZERO);
			redPack.setExpendBalance(BigDecimal.ZERO);
			if (2 != redPack.getType()) {
				activityCountList.add(redPack);
			}
		}
		return activityCountList;
	}
}
